<template>
  <div id="main">
    <h2>家长管理</h2>
    <div class="head">
      <el-button
        type="primary"
        style="margin:20px"
        @click="handleOpen('添加家长', 1)"
      >添加家长</el-button>
      <el-input
        v-model="searchTableInfo"
        placeholder="请输入搜索内容"
        style="width:240px;float: right;margin-right:20px;"
      />
    </div>
    <div id="table-area">
      <el-table
        v-loading="listLoading"
        :data="list.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <el-table-column label="序号" type="index" align="center">
          <template scope="scope">
            <span>{{ (currentPage - 1) * pagesize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" prop="parentName" label="家长姓名" />

        <el-table-column align="center" prop="parentBirth" label="出生日期" />

        <el-table-column align="center" prop="parentCall" label="家长电话" />

        <el-table-column align="center" prop="parentSex" label="家长性别" />

        <el-table-column align="center" label="操作">
          <template slot-scope="Scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="handleOpen('修改课程', 2, Scope.row.parentId)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(Scope.row.parentId, Scope.row.parentName)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div id="pages">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[5, 10]"
          :page-size="pagesize"
          layout="total, sizes,prev, pager, next"
          :total="list.length"
          prev-text="上一页"
          next-text="下一页"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog
      title=""
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
    >
      <el-form ref="parent" :model="parent" label-position="top" :rules="rules">
        <el-form-item
          prop="parentName"
          label="家长姓名"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="parent.parentName"
            maxlength="20"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          prop="parentBirth"
          label="家长生日"
          :label-width="formLabelWidth"
        >
          <el-date-picker
            v-model="parent.parentBirth"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item
          prop="parentCall"
          label="家长电话"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="parent.parentCall"
            autocomplete="off"
            maxlength="11"
            onkeyup="this.value=this.value.replace(/[^\d.]/g,'');"
          />
        </el-form-item>
        <el-form-item
          prop="parentEmail"
          label="家长邮箱"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="parent.parentEmail"
            maxlength="32"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          prop="parentAdd"
          label="家庭住址"
          :label-width="formLabelWidth"
        >
          <el-input v-model="parent.parentAdd" autocomplete="off" />
        </el-form-item>
        <el-form-item
          prop="parentEducationalLevel"
          label="家长文化水平"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="parent.parentEducationalLevel"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          prop="parentOccupation"
          label="家长职业"
          :label-width="formLabelWidth"
        >
          <el-input v-model="parent.parentOccupation" autocomplete="off" />
        </el-form-item>
        <el-form-item
          prop="parentSex"
          label="家长性别"
          :label-width="formLabelWidth"
        >
          <!-- <el-input v-model="parent.parentSex" autocomplete="off" /> -->
          <el-radio v-model="parent.parentSex" label="0">女</el-radio>
          <el-radio v-model="parent.parentSex" label="1">男</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleClose">取 消</el-button>
        <el-button
          v-if="editType == 2"
          type="primary"
          @click="handleUpdate('parent')"
        >修 改</el-button>
        <el-button
          v-if="editType == 1"
          type="primary"
          @click="handleAdd('parent')"
        >添 加</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  addParent,
  updateParent,
  deleteParent,
  getParentById,
  getAllParent
} from '@/api/parent'
export default {
  data() {
    var checkphone = (rule, value, callback) => {
      // let phoneReg = /(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/;
      if (value == null) {
        callback(new Error('员工电话不能为空'))
      } else if (!this.isCellPhone(value)) {
        // 引入methods中封装的检查手机格式的方法
        callback(new Error('请输入正确的手机号!'))
      } else {
        callback()
      }
    }
    return {
      currentPage: 1, // 默认显示页面为1
      pagesize: 5, //    每页的数据条数
      url: process.env.VUE_APP_BASE_API + 'file/',
      imageUrl: '',
      // list: [],
      tableList: [],
      listLoading: false,
      dialogFormVisible: false,
      editType: 1, // 1 添加 2 修改
      parent: {},
      formLabelWidth: '200px',
      searchTableInfo: '',
      newParent: {
        parentId: '',
        parentName: '',
        parentCall: '',
        parentBirth: '',
        parentSex: ''
      },
      rules: {
        staffCall: [{ required: true, validator: checkphone, trigger: 'blur' }],
        staffEdu: [
          { required: true, message: '员工教育程度不能为空', trigger: 'blur' }
        ],
        staffEmail: [
          { required: true, validator: this.checkEmail, trigger: 'blur' }
        ],
        staffIdcard: [
          { required: true, message: '员工身份证号不能为空', trigger: 'blur' }
        ],
        staffJob: [
          { required: true, message: '员工职务不能为空', trigger: 'blur' }
        ],
        staffJurisdiction: [
          { required: true, message: '权限等级不能为空', trigger: 'blur' }
        ],
        staffMajor: [
          { required: true, message: '员工专业不能为空', trigger: 'blur' }
        ],
        staffName: [
          { required: true, message: '员工姓名不能为空', trigger: 'blur' }
        ],
        staffSchool: [
          { required: true, message: '员工职务不能为空', trigger: 'blur' }
        ]
      }

    }
  },
  computed: {
    // 根据计算属性模糊搜索
    list() {
      const searchTableInfo = this.searchTableInfo
      console.log(this.searchTableInfo)
      if (searchTableInfo) {
        // filter() 方法创建一个新的数组，新数组中的元素是通过检查指定数组中符合条件的所有元素。
        // 注意： filter() 不会对空数组进行检测。
        // 注意： filter() 不会改变原始数组。
        return this.tableList.filter(data => {
          console.log('success' + data)
          // some() 方法用于检测数组中的元素是否满足指定条件;
          // some() 方法会依次执行数组的每个元素：
          // 如果有一个元素满足条件，则表达式返回true , 剩余的元素不会再执行检测;
          // 如果没有满足条件的元素，则返回false。
          // 注意： some() 不会对空数组进行检测。
          // 注意： some() 不会改变原始数组。
          return Object.keys(data).some(key => {
            // indexOf() 返回某个指定的字符在某个字符串中首次出现的位置，如果没有找到就返回-1；
            // 该方法对大小写敏感！所以之前需要toLowerCase()方法将所有查询到内容变为小写。
            return (
              String(data[key])
                .toLowerCase()
                .indexOf(searchTableInfo) > -1
            )
          })
        })
      }
      return this.tableList
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 每页下拉显示数据
    handleSizeChange: function(size) {
      this.pagesize = size
    },
    // 点击第几页
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage
    },
    handleClick(row) {
      console.log(row)
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.obj.split(';')[0]
      this.lesson.lessonPic = this.imageUrl
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isImage =
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isImage) {
        this.$message.error('上传图片只能是 JPG或PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }
      return isImage && isLt2M
      // return true
    },
    fetchData() {
      this.tableList = []
      this.listLoading = true
      getAllParent().then(data => {
        this.newParent
        for (var i = 0; i < data.obj.length; i++) {
          this.newParent.parentId = data.obj[i].parentId
          this.newParent.parentName = data.obj[i].parentName
          this.newParent.parentCall = data.obj[i].parentCall
          this.newParent.parentBirth = data.obj[i].parentBirth
          if (data.obj[i].parentSex === '0') {
            this.newParent.parentSex = '女'
          }
          if (data.obj[i].parentSex === '1') {
            this.newParent.parentSex = '男'
          }
          this.tableList.push(this.newParent)
          this.newParent = {}
        }
        console.log(this.tableList)
        this.listLoading = false
      })
    },
    handleDelete(id, parentName) {
      this.$confirm('确认删除该家长？姓名为' + parentName).then(() =>
        deleteParent(id).then(data => {
          this.$notify({
            title: '操作成功',
            type: 'success'
          })
          const totalPage = Math.ceil((this.list.length - 1) / this.pagesize)
          const page =
            this.currentPage > totalPage ? totalPage : this.currentPage
          this.currentPage = this.currentPage < 1 ? 1 : page
          this.fetchData()
        })
      )
    },
    handleAdd(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          addParent(this.parent).then(resp => {
            this.$notify({
              title: '操作成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.parent = {}
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    handleOpen(title, type, id) {
      this.parent = {}
      this.dialogFormVisible = true
      this.title = title
      this.editType = type
      if (type === 2) {
        getParentById(id).then(resp => {
          console.log(resp)
          // this.imageUrl = resp.obj.lessonPic
          this.parent = resp.obj
          console.log(this.parent)
        })
      }
    },
    handleClose() {
      this.dialogFormVisible = false
      this.parent = {}
      this.imageUrl = ''
    },
    handleUpdate(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(this.parent)
          updateParent(this.parent).then(resp => {
            this.$notify({
              title: '修改成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    isCellPhone(val) {
      if (!/^1[3456789]\d{9}$/.test(val)) {
        return false
      } else {
        return true
      }
    },
    checkEmail(rule, value, callback) {
      if (!value) {
        return callback(new Error('员工邮箱不能为空'))
      } else {
        const reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入有效的电子邮箱！'))
        }
      }
    }
  }
}
</script>

<style scoped>
#main {
  margin-left: 5px;
  margin-right: 5px;
}
#table-area {
  margin-left: 10px;
  margin-right: 10px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 360px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 360px;
  height: 150px;
  display: block;
}
</style>
